package com.cpr.ams.web.controller;


import com.cpr.ams.bean.BaseUser;
import com.cpr.ams.bean.extend.BaseUserExtend;
import com.cpr.ams.exception.AmsException;
import com.cpr.ams.service.IBaseUserService;
import com.cpr.ams.util.JwtTokenUtil;
import com.cpr.ams.util.Result;
import com.cpr.ams.util.StatusCode;
import com.cpr.ams.vm.UserVM;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 用户控制类
 * @Author: GX Cui
 * @Date 1:48 下午 2021/4/12
 */
@Api(value = "用户Controller",tags = {"用户操作接口"})
@Validated
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IBaseUserService baseUserService;

    @PostMapping("login")
    public Result login(@RequestBody UserVM userVM){
        try{
            // 1. 认证用户的用户名和密码
            BaseUser user = baseUserService.login(userVM);
            // 2. 如果登录成功产生token,将token缓存起来，返回
            String token = JwtTokenUtil.createJWT(user.getId(), user.getUserName());
            // 3. 如果登录失败
            Map<String,String> map = new HashMap<>();
            map.put("token",token);
            return Result.success(map);
        }catch (AmsException ams){
            if(ams.getStatusCode().getCode() == 20004){
                return Result.fail(StatusCode.USER_NOT_EXIST);
            }else if(ams.getStatusCode().getCode() == 20002){
                return Result.fail(StatusCode.USER_LOGIN_ERROR);
            }else {
                return Result.fail(StatusCode.UNKNOWN_ERROR);
            }
        }
    }

    @ApiOperation(value = "通过token获取用户的基本信息")
    @GetMapping("info")
    public Result info(String token){
        // 1. 通过token获取用户信息  {id,use,gender,roles:[]}
        int id = Integer.parseInt(JwtTokenUtil.getUserId(token,JwtTokenUtil.base64Secret));
        BaseUserExtend baseUserExtend = baseUserService.findById(id);
        return Result.success(baseUserExtend);
    }

    @PostMapping("logout")
    public Result logout(){
        // 1. 登录， token从缓存中移除掉
        return Result.success("退出成功");
    }


}
